接下來要在頁面上按下按鈕跳頁
以及按了左邊 header icon 回上一頁
正所謂有去有回才不會不知道怎麼辦!
const Home = ({navigation}) => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Home Screen</Text>
// 加入按鈕
<TouchableOpacity
onPress={() => {
navigation.navigate('IconScreen', { title: "icon頁" });
}}
style={{backgroundColor: '#aaa', padding: 5, margin: 5}}
activeOpacity={0.6}>
<Text>來去別頁!</Text>
</TouchableOpacity>
// End
</View>
);
};
PS. 切記文字都需要放在 Text 內唷!
整個 App.js
import 'react-native-gesture-handler';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {
Text,
View,
Image,
Platform,
StyleSheet,
TouchableOpacity,
} from 'react-native';
import IconScreen from '@screens/IconScreen';
import {assets} from '@src/constants';
const Stack = createStackNavigator();
const headerOptions = ({route, navigation}) => ({
title: route.params ? route.params.title : '',
headerTintColor: 'black', // 字體顏色
headerTitleStyle: {alignSelf: 'center', fontSize: 16}, // header 樣式
headerStyle: {
height: Platform.OS === 'ios' ? 88 : 44,
}, // 使用裝置來判斷 header 的高度
headerRight: () => (
<Image source={assets.actionPrimary} style={[styles.actionPrimary]} />
), // 右邊放入 icon
headerLeft: () => (
<TouchableOpacity
onPress={() => {
navigation.goBack();
}}>
<Image
source={assets.actionPrimary}
style={[styles.actionPrimary]}
onPress={() => {
navigation.goBack();
}}
/>
</TouchableOpacity>
// 左邊放入icon 並使用 navigation.goBack() 及 backToHome() 回上一頁
),
});
const Home = ({navigation}) => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Home Screen</Text>
<TouchableOpacity
onPress={() => {
navigation.navigate('IconScreen', {title: 'icon頁'});
}}
style={{backgroundColor: '#aaa', padding: 5, margin: 5}}
activeOpacity={0.6}>
<Text>來去別頁!</Text>
</TouchableOpacity>
</View>
);
};
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={Home} options={headerOptions} />
<Stack.Screen
name="IconScreen"
component={IconScreen}
options={headerOptions}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
const styles = StyleSheet.create({
actionPrimary: {
width: 56,
height: 56,
marginRight: 6,
},
});
export default App;
以上設定完後,簡單的切頁、換頁傳遞資料及回上一頁就完成了!!
頁面傳遞資料可以使用 navigation.navigate(A ,{ becca: "卡卡" }), 而到 A 頁面要讀取的話使用 route.params.becca="卡卡"
其實 options 還有包含像是 native 的換頁動畫及手勢~ 大家可以再參考官方 doc 研究一下!
Day 15 done! 請多多指教~